<template>
  <div class="inner-container">
    <!-- 查询条件 -->
    <div class="x-header">
      <span class="navTitle">企业查询</span>
      <el-divider></el-divider>
      <el-form label-width="90px" ref="formSearch" :model="formSearch">
        <el-row>
          <el-col :span="8">
            <el-form-item label="企业名称 :" prop="name">
              <el-input placeholder="请输入企业名称" v-model="formSearch.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务类型 :" prop="type">
              <el-select style="width:100%" v-model="formSearch.type">
                <el-option
                  v-for="(item, index) in businessTypes"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="成立时间 :" prop="createTime">
              <el-date-picker
                v-model="formSearch.createTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width:100%"
                value-format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-button
              type="primary"
              style="margin-left:90px"
              icon="el-icon-search"
              @click="handleQueryData"
            >查询</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset('formSearch')">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 企业列表 -->
    <div class="x-record_list">
      <div class="navTitle">企业列表</div>
      <el-divider></el-divider>
      <div class="btn_list">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddEnterprise">新增</el-button>
        <el-button
          type="danger"
          icon="el-icon-delete"
          @click="handleBatchDelete"
          :disabled="multipleData.length == 0"
        >批量删除</el-button>
      </div>
      <el-table
        :data="tableData"
        style="width:100%;min-height:150px"
        v-loading="isLoadingTable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column type="index" width="55" align="center"></el-table-column>
        <el-table-column label="企业名称" prop="name" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column label="办公地址" prop="officeAddress" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column label="法定代表人" prop="legalRepresentName" align="center"></el-table-column>

        <el-table-column label="类型" prop="type" align="center"></el-table-column>
        <el-table-column label="统一社会信用代码" prop="uniformSocialCreditCode" align="center"></el-table-column>
        <el-table-column label="等级" prop="level" align="center"></el-table-column>
        <el-table-column label="联系人" prop="contactName" align="center"></el-table-column>
        <el-table-column label="联系电话" prop="contactMobilePhone" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="250">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleDetail(scope.row)"
              v-loading.fullscreen.lock="loadingDetail"
            >详情</el-button>
            <el-button
              type="primary"
              size="mini"
              @click="handleEdite(scope.row)"
              v-loading.fullscreen.lock="loadingEdite"
            >编辑</el-button>
            <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="text-center">
        <el-pagination
          :current-page.sync="currentPage"
          :page-size="10"
          layout="prev, pager, next, jumper"
          :total="total"
          style="margin-top:20px"
          @current-change="handleCurrentPage"
        ></el-pagination>
      </div>
    </div>
    <!-- 新增弹框 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="dialogTitle"
      :visible.sync="enterpriseDialogVisible"
      style="margin: 10vh 0;"
      top="0"
      @close="handleCloseDialog('enterpriceForm')"
    >
      <div>
        <el-form
          label-position="top"
          :model="dialogFormData"
          ref="enterpriceForm"
          :rules="enterpriceFormRules"
        >
          <el-row>
            <el-col :span="12" class="px-1">
              <el-form-item label="企业名称 :" prop="name">
                <el-input
                  placeholder="请输入企业名称"
                  v-model="dialogFormData.name"
                  :readonly="isReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="注册地址 :" prop="registeredAddress">
                <el-input
                  placeholder="请输入注册地址"
                  v-model="dialogFormData.registeredAddress"
                  :readonly="isReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="注册资本(万元) :" prop="registeredCapital">
                <el-input
                  type="number"
                  placeholder="请输入注册资本"
                  v-model="dialogFormData.registeredCapital"
                  :readonly="isReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="办公地址 :" prop="officeAddress">
                <el-input
                  placeholder="请输入办公地址"
                  v-model="dialogFormData.officeAddress"
                  :readonly="isReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="申请业务类型 :" prop="type">
                <el-select style="width:100%" v-model="dialogFormData.type" :disabled="isReadonly">
                  <el-option
                    v-for="(item, index) in businessTypes"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="资质等级 :" prop="level">
                <el-select style="width:100%" v-model="dialogFormData.level" :disabled="isReadonly">
                  <el-option
                    v-for="(item, index) in qualificationLevels"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="权限 :" prop="permissionList">
                <el-select
                  style="width:100%"
                  multiple
                  v-model="dialogFormData.permissionList"
                  :disabled="isReadonly"
                >
                  <el-option label="测绘单位" value="MAPPING"></el-option>
                  <el-option label="施工单位" value="CONSTRUCT"></el-option>
                  <el-option label="监理单位" value="SUPERVISE"></el-option>
                  <el-option label="规划设计单位" value="PLANNING"></el-option>
                  <el-option label="工程复核单位" value="REVIEW"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="统一社会信用代码 :" prop="uniformSocialCreditCode">
                <el-input
                  placeholder="请输入统一社会信用代码"
                  v-model="dialogFormData.uniformSocialCreditCode"
                  :readonly="isReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="工商执照发证机关 :" prop="certificateOrgan">
                <el-input
                  placeholder="请输入工商执照发证机关"
                  v-model="dialogFormData.certificateOrgan"
                  :readonly="isReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="工商执照发证日期 :" prop="certificateTime">
                <el-date-picker
                  v-model="dialogFormData.certificateTime"
                  type="date"
                  style="width:100%"
                  :readonly="isReadonly"
                  placeholder="选择日期"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="成立日期 :" prop="createTime">
                <el-date-picker
                  v-model="dialogFormData.createTime"
                  type="date"
                  style="width:100%"
                  :readonly="isReadonly"
                  placeholder="选择日期"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1">
              <el-form-item label="营业期限 :" prop="businessTime">
                <el-date-picker
                  v-model="dialogFormData.businessTime"
                  type="date"
                  style="width:100%"
                  placeholder="选择日期"
                  :readonly="isReadonly"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <!-- 编辑是才会出现 -->
            <el-col :span="12" class="px-1" v-show="submitType == 1">
              <el-form-item label="法人代表 :">
                <el-select
                  style="width:100%"
                  v-model="dialogFormData['legalRepresentId']"
                  @change="changeSelect"
                  :disabled="isReadonly"
                >
                  <el-option
                    v-for="(item, index) in enterpriseStaff"
                    :key="item.userId + 'a'"
                    :label="item.name"
                    :value="item.userId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1" v-show="submitType == 1">
              <el-form-item label="联系人 :">
                <el-select
                  style="width:100%"
                  v-model="dialogFormData['contactId']"
                  @change="changeSelect"
                  :disabled="isReadonly"
                >
                  <el-option
                    v-for="(item, index) in enterpriseStaff"
                    :key="item.userId + 'b'"
                    :label="item.name"
                    :value="item.userId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 详情才会出现 -->
            <el-col :span="12" class="px-1" v-show="submitType == 2">
              <el-form-item label="法人代表 :">
                <el-row>
                  <el-col :span="12">
                    姓名：{{
                    dialogFormData.legalRepresent
                    ? dialogFormData.legalRepresent.name
                    : "未知"
                    }}
                  </el-col>
                  <el-col :span="12">
                    性别：{{
                    dialogFormData.legalRepresent
                    ? dialogFormData.legalRepresent.gender == "MAN"
                    ? "男"
                    : "女"
                    : "未知"
                    }}
                  </el-col>
                  <el-col :span="12">
                    身份证号：{{
                    dialogFormData.legalRepresent
                    ? dialogFormData.legalRepresent.num
                    : "未知"
                    }}
                  </el-col>
                  <el-col :span="12">
                    手机号码：{{
                    dialogFormData.legalRepresent
                    ? dialogFormData.legalRepresent.mobilePhone
                    : "未知"
                    }}
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="px-1" v-show="submitType == 2">
              <el-form-item label="联系人 :">
                <el-row>
                  <el-col :span="12">
                    姓名：{{
                    dialogFormData.contact
                    ? dialogFormData.contact.name
                    : "未知"
                    }}
                  </el-col>
                  <el-col :span="12">
                    性别：{{
                    dialogFormData.contact
                    ? dialogFormData.contact.gender == "MAN"
                    ? "男"
                    : "女"
                    : "未知"
                    }}
                  </el-col>
                  <el-col :span="12">
                    身份证号：{{
                    dialogFormData.contact
                    ? dialogFormData.contact.num
                    : "未知"
                    }}
                  </el-col>
                  <el-col :span="12">
                    手机号码：{{
                    dialogFormData.contact
                    ? dialogFormData.contact.mobilePhone
                    : "未知"
                    }}
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" style="text-align: center;" v-show="submitType != 2">
        <el-button type="primary" @click="handleSubmit('enterpriceForm')">确定</el-button>
        <el-button @click="handleReset('enterpriceForm')">重置</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCompanyTable,
  getEnterpriseByID,
  enterpriseAdd,
  getEnterpriseDetailByID,
  enterpriseUpdate,
  getPersonDetailByID,
  getDeleteEnterpriseByID,
  getBatchDeleteEnterpriseByID
} from '@/api/project/integrity/company'
import moment from 'moment'
export default {
  data() {
    return {
      //查询条件
      formSearch: {
        name: '',
        type: '',
        createTime: ''
      },
      //表格
      isLoadingTable: false,
      tableData: [],
      //分页
      currentPage: 1,
      total: 0,
      //弹框参数
      dialogTitle: '企业管理-新增',
      enterpriseDialogVisible: false,
      //申请单位类型
      businessTypes: [
        { name: '测绘', value: '测绘' },
        { name: '规划设计与预算编制', value: '规划设计与预算编制' },
        { name: '招投标代理', value: '招投标代理' },
        { name: '工程监理', value: '工程监理' },
        { name: '工程施工', value: '工程施工' }
      ],
      //资质等级
      qualificationLevels: [
        { name: '甲级', value: '甲级' },
        { name: '乙级', value: '乙级' },
        { name: '丙级', value: '丙级' },
        { name: '丁级', value: '丁级' }
      ],
      //营业期限参数
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        },
        shortcuts: [
          {
            text: '永久',
            onClick(picker) {
              const date = new Date('9999-01-01')
              date.setTime(date.getTime())
              picker.$emit('pick', date)
            }
          }
        ]
      },
      //新增、编辑参数
      dialogFormData: {
        name: '',
        type: '',
        uniformSocialCreditCode: '',
        officeAddress: '',
        registeredAddress: '',
        level: '',
        registeredCapital: '',
        certificateOrgan: '',
        certificateTime: '',
        createTime: '',
        businessTime: '',
        legalRepresentId: '',
        contactId: '',
        permissionList: []
      },
      loadingDetail: false,
      loadingEdite: false,
      //新增、编辑类型判断
      submitType: 0, //0:新增，1:编辑，2:详情
      //表单验证规则
      enterpriceFormRules: {
        name: [{ required: true, message: '不能为空！', trigger: 'blur' }],
        registeredAddress: [
          { required: true, message: '不能为空！', trigger: 'blur' }
        ],
        registeredCapital: [
          { required: true, message: '不能为空！', trigger: 'blur' }
        ],
        officeAddress: [
          { required: true, message: '不能为空！', trigger: 'blur' }
        ],
        type: [{ required: true, message: '不能为空！', trigger: 'change' }],
        level: [{ required: true, message: '不能为空！', trigger: 'change' }],
        uniformSocialCreditCode: [
          { required: true, message: '不能为空！', trigger: 'blur' }
        ],
        certificateOrgan: [
          { required: true, message: '不能为空！', trigger: 'blur' }
        ],
        certificateTime: [
          {
            required: true,
            message: '不能为空！',
            type: 'date',
            trigger: 'change'
          }
        ],
        createTime: [
          {
            required: true,
            message: '不能为空！',
            type: 'date',
            trigger: 'change'
          }
        ],
        businessTime: [
          {
            required: true,
            message: '不能为空！',
            type: 'date',
            trigger: 'change'
          }
        ],
        permissionList: [
          { required: true, message: '不能为空！', trigger: 'change' }
        ]
      },
      //企业人员
      enterpriseStaff: [],
      //企业详情
      isReadonly: false,
      personDetail_1: null, //法人代表
      personDetial_2: null, //联系人
      //多选数据
      multipleData: []
    }
  },
  methods: {
    getInitTableData: function() {
      this.handleGetTableData()
    },
    //获取企业列表数据
    handleGetTableData: function(page) {
      this.isLoadingTable = true
      page ? (this.currentPage = page) : ''
      let params = {
        page: this.currentPage,
        size: 10
      }
      params = Object.assign(params, this.formSearch)
      params['createTimeStart'] =
        params['createTime'] && params['createTime'].length
          ? params['createTime'][0]
          : ''
      params['createTimeEnd'] =
        params['createTime'] && params['createTime'].length
          ? params['createTime'][1]
          : ''
      delete params['createTime']
      getCompanyTable(params).then(res => {
        this.isLoadingTable = false
        this.tableData = res.data.rows
        this.total = res.data.total
      })
    },
    //查询人员列表
    handleEnterpriseByID: function(id) {
      return new Promise((reject, resolve) => {
        let params = {
          enterpriseid: id
        }
        getEnterpriseByID(params).then(res => {
          this.enterpriseStaff = res.data
          reject()
        })
      })
    },
    //查询企业基本信息
    handleEnterpriseDetail: function(id) {
      return new Promise((reject, resolve) => {
        let params = {
          id: id
        }
        getEnterpriseDetailByID(params).then(res => {
          this.dialogFormData = res.data
          this.dialogFormData['permissionList'] = this.dialogFormData[
            'permissionList'
          ]
          this.dialogFormData['createTime'] = this.dialogFormData['createTime']
            ? new Date(this.dialogFormData['createTime'])
            : ''
          this.dialogFormData['certificateTime'] = this.dialogFormData[
            'certificateTime'
          ]
            ? new Date(this.dialogFormData['certificateTime'])
            : ''
          this.dialogFormData['businessTime'] = this.dialogFormData[
            'businessTime'
          ]
            ? new Date(this.dialogFormData['businessTime'])
            : ''
          this.dialogFormData['contactId'] = this.dialogFormData['contact']
            ? this.dialogFormData['contact'].userId
            : ''
          this.dialogFormData['legalRepresentId'] = this.dialogFormData[
            'legalRepresent'
          ]
            ? this.dialogFormData['legalRepresent'].userId
            : ''
          reject()
        })
      })
    },
    handleGetPersonDetail: function(id, type) {
      let params = {
        id: id
      }
      getPersonDetailByID(params).then(res => {
        if (type == 1) {
        }
      })
    },
    //查询
    handleQueryData: function() {
      this.handleGetTableData(1)
    },
    //重置
    handleReset: function(formName) {
      this.$refs[formName].resetFields()
    },
    //新增企业
    handleAddEnterprise: function() {
      this.enterpriseDialogVisible = true
      this.dialogTitle = '企业管理-新增'
      this.submitType = 0
    },
    //新增、编辑
    handleSubmit: function(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.dialogFormData))
          params['createTime'] = moment(params['createTime']).format(
            'YYYY-MM-DD HH:mm:ss'
          )
          params['certificateTime'] = moment(params['certificateTime']).format(
            'YYYY-MM-DD HH:mm:ss'
          )
          params['businessTime'] = moment(params['businessTime']).format(
            'YYYY-MM-DD HH:mm:ss'
          )
          params['permissionList'] = new Array(params['permissionList'])
          if (this.submitType == 0) {
            enterpriseAdd(params).then(res => {
              this.$message.success('操作成功！')
              this.handleGetTableData(1)
              this.enterpriseDialogVisible = false
            })
          } else {
            enterpriseUpdate(params).then(res => {
              this.$message.success('操作成功！')
              this.handleGetTableData()
              this.enterpriseDialogVisible = false
            })
          }
        }
      })
    },
    //弹框关闭回调
    handleCloseDialog: function(formName) {
      this.dialogFormData = {
        name: '',
        type: '',
        uniformSocialCreditCode: '',
        officeAddress: '',
        registeredAddress: '',
        level: '',
        registeredCapital: '',
        certificateOrgan: '',
        certificateTime: '',
        createTime: '',
        businessTime: '',
        legalRepresentId: '',
        contactId: '',
        permissionList: ''
      }
      this.$refs[formName].resetFields()
      this.enterpriseStaff = []
      this.isReadonly = false
    },
    //批量删除
    handleBatchDelete: function() {
      this.$confirm('此操作将批量删除企业, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(res => {
        let ids = this.multipleData
          .map(item => {
            return item.id
          })
          .join(',')
        getBatchDeleteEnterpriseByID({ ids }).then(res => {
          this.$message.success('操作成功！')
          this.handleGetTableData()
        })
      })
    },
    //详细
    handleDetail: async function(row) {
      this.submitType = 2
      this.isReadonly = true
      this.dialogTitle = '企业管理-基本信息'
      this.loadingDetail = true
      await this.handleEnterpriseDetail(row.id)
      await this.handleEnterpriseByID(row.id)
      this.loadingDetail = false
      this.enterpriseDialogVisible = true
    },
    //编辑
    handleEdite: async function(row) {
      this.submitType = 1
      this.dialogTitle = '企业管理-编辑'
      this.loadingEdite = true
      await this.handleEnterpriseDetail(row.id)
      await this.handleEnterpriseByID(row.id)
      this.loadingEdite = false
      this.enterpriseDialogVisible = true
    },
    //单个删除
    handleDelete: function(row) {
      this.$confirm('此操作将删除企业, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(res => {
        getDeleteEnterpriseByID({ id: row.id }).then(res => {
          this.$message.success('操作成功！')
          this.handleGetTableData()
        })
      })
    },
    //分页查询
    handleCurrentPage: function(page) {
      this.handleGetTableData(page)
    },
    //下拉选择强制刷新
    changeSelect: function() {
      this.$forceUpdate()
    },
    //多选回调
    handleSelectionChange: function(val) {
      this.multipleData = val
    }
  },
  created() {
    this.getInitTableData()
  }
}
</script>

<style lang="scss" scoped>
.inner-container {
  padding: 20px 30px;
  background-color: #fff;
  .x-header {
    .navTitle {
      font-size: 17px;
      font-weight: bold;
      font-family: PingFangSC-Regular;
      color: rgba(72, 73, 77, 1);
      margin-bottom: 20px;
    }
  }
  .x-record_list {
    .navTitle {
      font-size: 17px;
      font-weight: bold;
      font-family: PingFangSC-Regular;
      color: rgba(72, 73, 77, 1);
      margin: 20px 0;
    }
    .btn_list {
      // text-align: right;
      margin-bottom: 20px;
    }
  }
}
.px-1 {
  padding: 0 10px;
}
</style>
